﻿using JT808.Gateway.Abstractions;
using JT808.Gateway.Abstractions.Configurations;
using JT808.Gateway.MsgLogging;
using JT808.Gateway.Session;
using JT808.Gateway.Transmit;
using JT808.Protocol;
using JT808.Protocol.Enums;
using JT808.Protocol.Extensions;
using JT808.Protocol.MessageBody;
using JT808.Repository;
using JT808.Repository.Core;
using JT808.Repository.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;

namespace JT808.Gateway.SimpleServer.Impl
{
    public class JT808MessageHandlerImpl : JT808MessageHandler
    {
        private readonly ILogger logger;
        private readonly IJT808MsgLogging jT808MsgLogging;
        //private readonly JT808TransmitService jT808TransmitService;
        private readonly IOptionsMonitor<JT808Configuration> jT808ConfigurationOptionsMonitor;
        private readonly IJT808MsgReplyLoggingProducer msgReplyLoggingProducer;
        private readonly IJT808Config jT808Config;
        private readonly IJT808MsgProducer msgProducer;
        private readonly JT808DataRepository jT808DataRepostiory;

        public JT808MessageHandlerImpl(
            ILoggerFactory loggerFactory,
            //JT808TransmitService jT808TransmitService,
            IJT808MsgLogging jT808MsgLogging,
            IOptionsMonitor<JT808Configuration> jT808ConfigurationOptionsMonitor, IJT808MsgProducer msgProducer, IJT808MsgReplyLoggingProducer msgReplyLoggingProducer, IJT808Config jT808Config
            , JT808DataRepository jT808DataRepostiory
            ) 
            : base(jT808Config)
        {
            this.jT808ConfigurationOptionsMonitor = jT808ConfigurationOptionsMonitor;
            this.msgProducer = msgProducer;
            this.jT808DataRepostiory = jT808DataRepostiory;
            this.msgReplyLoggingProducer = msgReplyLoggingProducer;
            //this.jT808TransmitService = jT808TransmitService;
            this.jT808MsgLogging = jT808MsgLogging;
            logger = loggerFactory.CreateLogger<JT808MessageHandlerImpl>();
            //添加自定义消息
            HandlerDict.Add(0x9999, Msg0x9999);
        }

        /// <summary>
        /// 重写消息处理器
        /// </summary>
        /// <param name="request"></param>
        /// <param name="session"></param>
        public override byte[] Processor(in JT808HeaderPackage request)
        {
            //AOP 可以自定义添加一些东西:上下行日志、数据转发
            logger.LogDebug("可以自定义添加一些东西:上下行日志、数据转发");
            var parameter = (request.Header.TerminalPhoneNo, request.OriginalData);
            //转发数据（可同步也可以使用队列进行异步）
            //try
            //{
            //    jT808TransmitService.SendAsync(parameter);
            //}
            //catch (Exception ex)
            //{
            //    logger.LogError(ex,"");
            //}
            //上行日志（可同步也可以使用队列进行异步）
            jT808MsgLogging.Processor(parameter, JT808MsgLoggingType.up);
            //处理上行消息
            var down= base.Processor(request);
            //下行日志（可同步也可以使用队列进行异步）
            jT808MsgLogging.Processor((request.Header.TerminalPhoneNo, down), JT808MsgLoggingType.down);
            return down;
        }

        ///// <summary>
        ///// 重写自带的消息
        ///// </summary>
        ///// <param name="request"></param>
        //public override byte[] Msg0x0200(JT808HeaderPackage request)
        //{
        //    //logger.LogDebug("重写自带Msg0x0200的消息");
        //    logger.LogDebug($"重写自带Msg0x0200的消息{request.Header.TerminalPhoneNo}-{request.OriginalData.ToHexString()}");   
        //    return base.Msg0x0200(request);
        //}
        /// <summary>
        /// 终端注销
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public override byte[] Msg0x0003(JT808HeaderPackage request)
        {
            //修改设备状态(根据手机号？)如果注册后换卡呢？

            //断开
            saveMsgLog(request, 0);
            var package = JT808Serializer.Deserialize(request.OriginalData);
            return CommonReply(request);
        }
        /// <summary>
        /// 终端鉴权
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public override byte[] Msg0x0102(JT808HeaderPackage request)
        {
            JT808Package package;
            try
            {
                //查数据，判断，缓存code和手机号的关系。
                package = JT808Serializer.Deserialize(request.OriginalData, request.Version);

                saveMsgLog(request, 1);
            }
            catch (Exception ex)
            {
                saveMsgLog(request, -1);//解析失败
            }
            return CommonReply(request);
        }

        /// <summary>
        /// 位置信息汇报
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public override byte[] Msg0x0200(JT808HeaderPackage request)
        {
            logger.LogDebug("****位置信息汇报 Msg0x0200");
            var package = JT808Serializer.Deserialize(request.OriginalData);
            saveMsgLog(request, 1);
            return CommonReply(request);

        }
        public override byte[] Msg0x0100(JT808HeaderPackage request)
        {
            logger.LogDebug("****终端注册 Msg0x0100");
            //同一设备多次注册怎么处理？
            JT808Terminal jT808Terminal = new JT808Terminal();
            var package = JT808Serializer.Deserialize(request.OriginalData);
            saveMsgLog(request, 1);
            JT808_0x0100 regPackage = (JT808_0x0100)package.Bodies;
            jT808Terminal.AreaID = regPackage.AreaID.ToString();
            jT808Terminal.CityOrCountyId = regPackage.CityOrCountyId.ToString();
            jT808Terminal.Code = "J" + request.Header.TerminalPhoneNo;
            jT808Terminal.MakerId = regPackage.MakerId;
            jT808Terminal.PlateColor = regPackage.PlateColor;
            jT808Terminal.PlateNo = regPackage.PlateNo;
            jT808Terminal.Status = 1;
            jT808Terminal.TerminalId = regPackage.TerminalId;
            jT808Terminal.TerminalModel = regPackage.TerminalModel;
            logger.LogDebug("****终端注册 AddJT808Terminal");
            int id = jT808DataRepostiory.AddJT808Terminal(jT808Terminal);

            if (request.Version == JT808Version.JTT2019)
            {
                byte[] data = JT808Serializer.Serialize(JT808MsgId.终端注册应答.Create_终端注册应答_2019(request.Header.TerminalPhoneNo, new JT808_0x8100()
                {
                    Code = "J" + request.Header.TerminalPhoneNo,
                    JT808TerminalRegisterResult = JT808TerminalRegisterResult.成功,
                    AckMsgNum = request.Header.MsgNum
                }));
                return data;
            }
            else
            {
                byte[] data = JT808Serializer.Serialize(JT808MsgId.终端注册应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8100()
                {
                    Code = "J" + request.Header.TerminalPhoneNo,
                    JT808TerminalRegisterResult = JT808TerminalRegisterResult.成功,
                    AckMsgNum = request.Header.MsgNum
                }));
                return data;
            }
            //return base.Msg0x0100(request);
        }
        private int saveMsgLog(JT808HeaderPackage headerPackage, int responseStatus)
        {

            try
            {
                logger.LogDebug("****存储消息日志 saveMsgLog");
                JT808MsgLog log = new JT808MsgLog();
                log.MsgData = headerPackage.OriginalData;
                log.MsgFrom = false;
                log.MsgId = headerPackage.Header.MsgId;
                log.MsgNum = headerPackage.Header.MsgNum;
                log.MsgTime = DateTime.Now;
                log.PackageIndex = headerPackage.Header.PackageIndex;
                log.PackgeCount = headerPackage.Header.PackgeCount;
                log.ProtocolVersion = headerPackage.Header.ProtocolVersion;
                log.TerminalPhoneNo = headerPackage.Header.TerminalPhoneNo;
                log.ResponseResult = responseStatus;
                log.SessionId = "";// session.SessionID;
                                   //先保存消息日志
                return jT808DataRepostiory.AddMsgLog(log);

            }
            catch(Exception ex)
            {
                logger.LogError(ex, "");
                logger.LogDebug("****存储消息日志 出错 saveMsgLog");
            }
            finally
            {
                logger.LogDebug("****存储消息日志 完成 saveMsgLog");
            }
            return 0;
        }

        /// <summary>
        /// 自定义消息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public byte[] Msg0x9999(JT808HeaderPackage request)
        {
            logger.LogDebug("自定义消息");
            return default;
        }
    }
}
